from functools import wraps
from flask import session, redirect
import redis

from ..models import User, StudentCourse
from .error_code import *
from .exception import *
from .response_util import *
from config import ALLOWED_EXTENSIONS


def user_is_login(func):
    @wraps(func)
    def inner(*args, **kwargs):
        if "username" in session:
            return func(*args, **kwargs)
        else:
            return response(404, "User Not Login", {})
    return inner


def check_user_type_2(func):
    @wraps(func)
    def inner(*args, **kwargs):
        username = session.get("username")
        need_type = 2
        user = User.query.filter(User.username == username).first()
        if user.user_type < need_type:
            raise APIException(USERNAME_ILLEGAL)
        else:
            return func(*args, **kwargs)

    return inner


def check_user_type_3(func):
    @wraps(func)
    def inner(*args, **kwargs):
        username = session.get("username")
        need_type = 3
        user = User.query.filter(User.username == username).first()
        if user.user_type < need_type:
            raise APIException(USERNAME_ILLEGAL)
        else:
            return func(*args, **kwargs)

    return inner


def check_user_type_4(func):
    @wraps(func)
    def inner(*args, **kwargs):
        username = session.get("username")
        need_type = 4
        user = User.query.filter(User.username == username).first()
        if user.user_type < need_type:
            raise APIException(USERNAME_ILLEGAL)
        else:
            return func(*args, **kwargs)

    return inner


def is_student_belongs_course(course_id):
    username = session.get("username")
    user = User.query.filter(User.username == username).first()
    if user is None:
        raise APIException(USERNAME_ILLEGAL)

    if user.user_type == 1:
        student_course = StudentCourse.query.filter(StudentCourse.student_id == username,
                                                    StudentCourse.course_id == course_id).limit(1).first()
        if student_course is None:
            return False
    return True


class Redis:
    @staticmethod
    def connect(host='localhost', port=6379, db=0):
        r = redis.StrictRedis(host, port, db)
        return r

    def set_data(self, key, ex=None):
        self.hset("user", key, 1, ex)

    def get_data(self, key):
        return self.hget("user", key)

    def incr_data_by(self, key, amount=1):
        self.incrby("user", key, amount)

    def del_data(self, key):
        self.hdel("user", key)


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
